import type {
  PlasmoCSConfig,
  PlasmoCSUIJSXContainer,
  PlasmoCSUIProps,
  PlasmoGetShadowHostId,
  PlasmoRender
} from "plasmo"
import type { FC } from "react"
import { createRoot } from "react-dom/client"
import { Provider } from "react-redux"

import { PersistGate } from "@plasmohq/redux-persist/integration/react"

import { persistor, store, useAppDispatch } from "~store"

// import { showAllPriceInfo } from "~store/controller/jinritemaiProduct"

import "@Styles/priceCommodity.scss"

// import axios from 'axios';

import React from "react"

// 指定挂载站点
export const config: PlasmoCSConfig = {
  matches: ["https://fxg.jinritemai.com/*"]
}

// 获取抖店挂载节点
export const getRootContainer = () =>
  new Promise((resolve) => {
    const checkInterval = setInterval(() => {
      // const tabTitle = document.querySelector('.ecom-g-table-thead') document.querySelector('[class*=style_renderMiddleStyle]')
      const rooTtableTitle = document.getElementsByTagName("th")
      if (rooTtableTitle && rooTtableTitle.length) {
        for (let i = 0; i <= rooTtableTitle.length; i++) {
          const spanlist = rooTtableTitle[i] && rooTtableTitle[i].innerText
          const spanlistOut =
            rooTtableTitle[i + 1] && rooTtableTitle[i + 1].innerText
          if (spanlist === "价格" && spanlistOut === "总库存") {
            // console.log("spanlistOut", spanlistOut)
            const idKey = "menberconter-quterss625"

            if (!document.getElementById(idKey)) {
              const col = document.createElement("col")
              col.id = idKey
              // 在倒数第二个位置插入
              document
                .querySelector("colgroup")
                .insertBefore(
                  col,
                  document.querySelector("colgroup").children[3]
                )
              document.querySelector("colgroup").lastChild.style.width = "120px"
            }

            clearInterval(checkInterval)
            const rootContainer = document.createElement("th")
            rootContainer.className = "ecom-g-table-cell"
            rootContainer.id = "menberconter"
            rootContainer.style.width = "260px"
            rooTtableTitle[i].parentNode?.insertBefore(
              rootContainer,
              rooTtableTitle[i].nextSibling
            )
            resolve(rootContainer)
            break
          }
        }
      }
    }, 137)
  })
//   export const getShadowHostId: PlasmoGetShadowHostId = () => `menberconter`
const TaberTitleDom = () => {
  //   const dispatch = useAppDispatch()
  return (
    <>
      <div className="prenttaber" onClick={() => render}>
        最终价格
        {/* <span onClick={() => getdata()}>点击测试请求</span> */}
        {/* <span onClick={() => dispatch(showAllPriceInfo())}>点击查看全部</span> */}
      </div>
    </>
  )
}

// 创建dom元素
const PlasmoOverlay: FC<PlasmoCSUIProps> = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <TaberTitleDom />
      </PersistGate>
    </Provider>
  )
}
// render
export const render: PlasmoRender<PlasmoCSUIJSXContainer> = async ({
  createRootContainer
}) => {
  if (!createRootContainer) return
  const rootContainer = await createRootContainer()
  const root = createRoot(rootContainer)
  root.render(<PlasmoOverlay />)
  //   const MutationObserver =
  //     window.MutationObserver ||
  //     window["WebKitMutationObserver"] ||
  //     window["MozMutationObserver"]
  // 创建MutationObserver实例，返回一个观察者对象
  let titer: any = null
  let saddkey = false
  setInterval(async (_) => {
    const menberconter = document.getElementById("menberconter")
    const activterStata = document.querySelector(".ecom-g-tabs-tab-active")?.[
      "innerText"
    ]
    if (!activterStata) return
    const interConter = ["已封禁", "全部", "售卖中", "已下架"]
    interConter.filter((item) => {
      return activterStata.includes(item)
    })
    if (
      !menberconter &&
      interConter.filter((item) => {
        return activterStata.includes(item)
      }).length > 0 &&
      location.pathname === "/ffa/g/list"
    ) {
      if (saddkey) return
      saddkey = true
      if (!titer) {
        titer = setTimeout(async (_) => {
          saddkey = false
          clearTimeout(titer)
          titer = null
        }, 1000)
      }

      const rootContainer = await createRootContainer()
      const root = createRoot(rootContainer)
      root.render(<PlasmoOverlay />)
    }
  }, 178)
  //   const mutation = new MutationObserver(async function (
  //     mutationRecoards,
  //     observer
  //   ) {
  //     if (titer) {
  //       clearTimeout(titer)
  //       titer = null
  //     }
  //     titer = setTimeout(async () => {
  //       const menberconter = document.getElementById("menberconter")
  //       const activterStata = document.querySelector(".ecom-g-tabs-tab-active")?.["innerText"]
  //       const interConter = ["已封禁", "全部", "售卖中", "已下架"]
  //       interConter.filter((item) => {
  //         return activterStata.includes(item)
  //       })
  //       if (
  //         !menberconter &&
  //         interConter.filter((item) => {
  //           return activterStata.includes(item)
  //         }).length > 0
  //       ) {
  //         const rootContainer = await createRootContainer()
  //         const root = createRoot(rootContainer)
  //         root.render(<PlasmoOverlay />)
  //       }
  //     }, 1)
  //   })
  //   const container:any = document.querySelector(".ecom-g-tabs-nav-list")
  //   const options = {
  //     attributes: true,
  //     // characterData: true,
  //     // childList: true,
  //     subtree: true
  //     // attributeOldValue: true,
  //     // characterDataOldValue: true
  //   }
  //   mutation.observe(container, options)
}

export default PlasmoOverlay
